import { useState, useCallback } from 'react';
import { useCountDown } from './useCountDown'
import { sendMobileCode, sendRetrieveVerifyEmail } from '~/api/loginApi';
import { useTranslation } from 'react-i18next';

export function useAuthCode() {
    const { t } = useTranslation();
    const [loading, setLoading] = useState(false);
    const [authCode, setAuthCode] = useState('');
    const [count, setCountDown] = useState(58000);
    const { seconds, isEnd } = useCountDown({ count });
    const fetchAuthCode = useCallback(async (mobile, action = 'actionLogin') => {
        setLoading(true);
        if (action == 'actionLogin') {
            // 手机号获取验证码
            const res = await sendMobileCode({ mobile })
            setLoading(false);
            setCountDown(59000);
            const verifyCode = res.send_code
            if (verifyCode) {
                setAuthCode(verifyCode);
            } else {
                Toast.show({ content: t('login.t11'), layout: 'top' });
            }
        } else {
            const res = await sendRetrieveVerifyEmail({ email: mobile })
            setLoading(false);
            setCountDown(59000);
            if (res.status == 1) {
                Toast.show({ content: t('login.t39'), layout: 'top' });
            } else {
                Toast.show({ content: t('login.t24'), layout: 'top' });
            }
            // 邮箱再次获取验证码
        }

    }, []);

    return { fetchAuthCode, authCode, loading, countDown: isEnd ? '' : seconds };
}
